// import Vue from 'vue'
import axios from 'axios'
import router from '@/router'
import store from '@/store'
import qs from 'qs'
import merge from 'lodash/merge'
import { getParam } from '@/utils/parameter'
import { logout } from '@/utils'

const http = axios.create({
  baseURL: '',
  timeout: 15000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
    // 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
    // 'Content-Type': 'multipart/form-data'
  }
})

// http 请求拦截器 1.给请求头带上accessToken
http.interceptors.request.use(request => {
  const url = request.url
  const urlLast = url.split('/')[url.split('/').length - 1]
  const token = (urlLast === 'refresh') ? store.state.user.refreshToken : store.state.user.accessToken
  request.headers.Authorization = token
  return request
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
http.interceptors.response.use(response => {
  // 401, token失效/格式错误 or 用户登录失败
  if (response.data && response.data.code === 401) {
    logout()
    router.push({ name: 'login' })
  } else if (response.data && response.data.code === 2001) {
    // 2001,token过期,根据refreshToken重新获取
    return store.dispatch('user/refresh_token').then(res => {
      return http.request(response.config)
    }).catch(e => {
      console.error('refreshToken Error => ', e)
      router.push({ name: 'login' })
    })
  }
  return response
}, error => {
  return Promise.reject(error)
})

/**
 * 请求地址处理 非生产环境 && 开启代理, 接口前缀统一使用[/api/]前缀做代理拦截!
 * @param {*} actionName action方法名称
 */
http.adornUrl = (actionName) => {
  // return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/api' : window.g.ApiUrl) + actionName
  const realUrl = getParam('userMockJS') ? '' : getParam('apiUrl')
  return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/api' : realUrl) + actionName
}

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = false) => {
  var defaults = {
    't': new Date().getTime()
  }
  return openDefultParams ? merge(defaults, params) : params
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式 默认json, 若修改contentType为application/x-www-form-urlencoded,则选择qs序列化
 */
http.adornData = (data = {}, openDefultdata = false, contentType = 'json') => {
  var defaults = {
    't': new Date().getTime()
  }
  data = openDefultdata ? merge(defaults, data) : data
  return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}

// store.dispatch('user/refresh_token', result.data)
function reFreshToken () {
  http.get(http.adornUrl('/login/refresh')).then(response => response.data)
}

export default http
